package ch3;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁降级示例
 * ReentrantReadWriteLock支持锁的降级（Downgrade），即一个线程持有读写锁的写锁情况下，可以继续申请获得相应的读锁
 * 但是ReentrantReadWriteLock不支持锁的升级
 */

public class ReadWriteLockDowngrade {
    private final ReadWriteLock rwLock = new ReentrantReadWriteLock();
    private final Lock readLock = rwLock.readLock();
    private final Lock writeLock = rwLock.writeLock();

    public void operationWithLockDowngrade() {
        boolean readLockAcquired = false;
        writeLock.lock();
        try {
            // 对共享数据进行更新
            // ...
            // 当前线程在持有写锁的情况下申请读锁readLock
            readLock.lock();
            readLockAcquired = true;
        } finally {
            writeLock.unlock();
        }
        if (readLockAcquired) {
            try {
                // 读取共享数据
                // ...
            } finally {
                readLock.unlock();
            }
        } else {
            // ...
        }
    }
}
